package com.tuanbiao.base;

import android.annotation.SuppressLint;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.tuanbiao.R;
import com.tuanbiao.base.action.ToastAction;

import java.util.HashMap;

/**
 * @author abiao
 * @date 2022/5/25 10:35
 * @description:
 */
public abstract class BaseSelectAdapter<T> extends BaseQuickAdapter<T, BaseViewHolder> implements ToastAction {
    /**
     * 选择对象集合
     */
    @SuppressLint("UseSparseArrays")
    private final HashMap<Integer, T> mSelectSet = new HashMap<>();
    /**
     * 最小选择数量
     */
    private int mMinSelect = 1;
    /**
     * 最大选择数量
     */
    private int mMaxSelect = Integer.MAX_VALUE;

    public BaseSelectAdapter(int layoutResId) {
        super(layoutResId);
    }

    private void setSelect(int... positions) {
        for (int position : positions) {
            mSelectSet.put(position, getItem(position));
        }
        notifyDataSetChanged();
    }

    private void setMaxSelect(int count) {
        mMaxSelect = count;
    }

    private void setMinSelect(int count) {
        mMinSelect = count;
    }

    private int getMinSelect() {
        return mMinSelect;
    }

    private void setSingleSelect() {
        setMaxSelect(1);
        setMinSelect(1);
    }

    private boolean isSingleSelect() {
        return mMaxSelect == 1 && mMinSelect == 1;
    }

    private HashMap<Integer, T> getSelectSet() {
        return mSelectSet;
    }

    public void select(int position) {
        if (mSelectSet.containsKey(position)) {
            // 当前必须不是单选模式才能取消选中
            if (!isSingleSelect()) {
                mSelectSet.remove(position);
                notifyItemChanged(position);
            }
        } else {
            if (mMaxSelect == 1) {
                mSelectSet.clear();
                notifyDataSetChanged();
            }

            if (mSelectSet.size() < mMaxSelect) {
                mSelectSet.put(position, getItem(position));
                notifyItemChanged(position);
            } else {
                showShort(String.format(getContext().getString(R.string.select_max_hint), mMaxSelect));
            }
        }
    }

    protected boolean containsKey(int position) {
        return mSelectSet.containsKey(position);
    }

    protected void clearSelect() {
        mSelectSet.clear();
        notifyDataSetChanged();
    }

}
